我有多个布局,这取决于一些共享的打字稿文件,这就是为什么我要与多个使用webpack的布局共享这些文件的原因。
我正在尝试在jquery
中加入ajax.ts
并收到此错误:
ERROR in ../_shared/ajax.ts
Module not found: Error: Can't resolve 'jquery' in '{...}/layouts/_shared'
_shared / ajax.ts:
import * as $ from 'jquery';
export class AjaxListener {
constructor(){
// use jquery with $
}
}
layoutA / app.ts:
import { AjaxListener } from "../_shared/ajax";
import { App } from "../_shared/app";
let app = new App();
let ajaxListener = new AjaxListener();
我的文件夹结构如下所示:
/layouts
/_shared
/ajax.ts
/app.ts
/layoutA
/app.ts
/webpack.config.js
/package.json (contains "@types/jquery": "^2.0.47" and "jquery": "^3.2.1")
/tsconfig.json
tsconfig.json:
{
"compilerOptions": {
"module": "es6",
"target": "es6",
"sourceMap": true
},
"exclude": [
"node_modules",
"typings/browser",
"typings/browser.d.ts",
"typings/main",
"typings/main.d.ts"
]
}
webpack.config.js:
const ExtractTextPlugin = require("extract-text-webpack-plugin");
var path = require("path");
var distPath = path.join(__dirname, "dist");
module.exports = [
{
entry: {
app: ['./app.sass', './app.ts']
},
resolve: {
extensions: [".tsx", ".js", ".ts", ".sass"]
},
cache: false,
output: {
path: distPath,
filename: "[name]_scripts.js"
},
module: {
rules : [
{
enforce: 'pre',
// "test" is commonly used to match the file extension
test: /\.js$/,
loader: "source-map-loader"
},
{
// "test" is commonly used to match the file extension
test: /\.tsx?$/,
exclude: [/node_modules/],
use: [ 'babel-loader', 'ts-loader' ]
},
{
test: /\.sass$/,
use: [
{
loader: "style-loader" // creates style nodes from JS strings
},{
loader: "css-loader", options: { sourceMap: true } // translates CSS into CommonJS
},{
loader: "sass-loader", options: { sourceMap: true } // compiles Sass to CSS
}
]
}
]
},
devtool: "eval"
}
]
如果我尝试在layoutA / app.ts文件(webpack root)中导入jquery,它可以正常工作。由于ajax.ts位于此文件夹之外,这是在这些文件中导入jquery,lodash等库的最佳方法吗?
答案 0 :(得分:0)
在上下文中加载js库的最佳方法必须遵循以下几点:
"files":[
"node_modules/@types/jquery/index.d.ts",
"node_modules/@types/requirejs/index.d.ts",
]
require(["jquery", "urijs"], function($, uri) {
// your code
});
其他说明:
import {Car} from "./classes/Car";
希望能帮到你,获得一个合适的结构!
补充:
请尝试以下操作:在ayax.ts中引用js库,如:
private example = require("./[path to npm library]/node_modules/test/src/test.js");
如果在require命令中调用库名如'test',则无法解析'test'。它尝试解析package.json并且找不到它,因为它在root之外。